import { PageContainer } from '@ant-design/pro-layout';
import { Button, message } from 'antd';
import { FormattedMessage } from 'umi';
import ProTable from '@ant-design/pro-table';
import { DrawerForm, ProFormText, ProFormSelect, ProFormDigit, ProFormTextArea } from '@ant-design/pro-form';
import React, { useState, useRef } from 'react';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import { PlusOutlined } from '@ant-design/icons';
import { ProductType } from '../../../model';
import { discountList, addDiscount, editDiscount, deleteDiscount, productList } from '../service';
import { useEffect } from 'react';
import { priceOption } from '@/utils/utils';
export default (() => {
  const [showCreate, setShowCreate] = useState(false);
  const actionRef = useRef<ActionType>();
  const [proData, setProData] = useState([]);
  const [proEnum, setProEnum] = useState({});

  async function productData() {
    var res = await productList({
      pageSize: 1000
    });
    var obj = {};
    res.data = res.data.reduce(function (item: any, next: any) {
      if (!obj[next.product_name]) {
        obj[next.product_name] = {
          text: next.product_name
        };
        item.push(next);
      }

      return item;
    }, []);
    setProData(res.data.map((item: any) => {
      return {
        label: item.product_name,
        value: item.product_name
      };
    }));
    setProEnum(obj);
  }

  useEffect(() => {
    productData();
    return function cleanup() {};
  }, []); //表头信息以及表值设置

  const columns: ProColumns<ProductType>[] = [{
    title: '规则编码',
    dataIndex: 'ruleCode',
    width: 100,
    editable:false,
    formItemProps: (form, {
      rowIndex
    }) => {
      return {
        rules: [{
          required: true,
          message: '此项为必填项'
        }]
      };
    }
  }, {
    title: '价格体系',
    dataIndex: 'ruleType',
    valueType: 'select',
    width: 100,
    valueEnum: priceOption(),
  }, {
    title: '产品名称',
    dataIndex: 'productName',
    valueType: 'select',
    valueEnum: proEnum,
    formItemProps: (form, {
      rowIndex
    }) => {
      return {
        rules: [{
          required: true,
          message: '此项为必填项'
        }]
      };
    }
  }, {
    title: '数量≥',
    dataIndex: 'discountNum',
    hideInSearch: true,
    valueType: 'digit',
    width: 100,
    formItemProps: (form, {
      rowIndex
    }) => {
      return {
        rules: [{
          required: true,
          message: '此项为必填项'
        }]
      };
    }
  }, {
    title: '数量≤',
    dataIndex: 'discountNum2',
    valueType: 'digit',
    hideInSearch: true,
    width: 100
  }, {
    title: '优惠后价格',
    dataIndex: 'discountPrice',
    hideInSearch: true,
    valueType: 'money',
    width: 150,
    formItemProps: (form, {
      rowIndex
    }) => {
      return {
        rules: [{
          required: true,
          message: '此项为必填项'
        }]
      };
    }
  }, {
    title: '创建日期',
    dataIndex: 'createTime',
    editable: false,
    hideInSearch: true,
    renderText: (_, record: any) => {
      return record.createTime.substr(0, 10);
    }
  }, {
    title: '更新日期',
    dataIndex: 'updateTime',
    editable: false,
    hideInSearch: true,
    renderText: (_, record: any) => {
      return record.updateTime.substr(0, 10);
    }
  }, {
    title: '规则说明',
    dataIndex: 'ruleInfo',
    hideInSearch: true,
    valueType: 'textarea'
  }, {
    title: '操作',
    valueType: 'option',
    width: 200,
    render: (text, record, _, action) => [<a key='editable' onClick={() => {
      action.startEditable?.(record.id);
    }} >
          编辑
        </a>]
  }];
  return <PageContainer>
    <ProTable actionRef={actionRef} scroll={{x:1200}} headerTitle={<>优惠规则<span style={{
        color: '#f10000',
        marginLeft: 20
      }}>特殊价格商品不参与优惠</span><span></span></>} pagination={{
      pageSizeOptions: ['20', '100', '500']
    }} request={(params, sorter, filter) => {
      // if (params.ruleType === '4') {
      //   params.ruleType = '0';
      // }

      return discountList({ ...params,
        filter
      });
    }} columns={columns} rowKey='id' search={{
      labelWidth: 120
    }} toolBarRender={() => [<Button type='primary' key='primary' onClick={() => {
      setShowCreate(true);
    }}>
          <PlusOutlined/> <FormattedMessage id='pages.searchTable.new' defaultMessage='新建'/>
        </Button>]} toolbar={{
      settings: []
    }} editable={{
      type: 'multiple',
      onSave: async (values: any, record: any) => {
        var val = await editDiscount(record);
        if (val.errorCode === '200') {
          message.success('更新成功');
          return true;
        } else {
          message.error(val.errorMessage);
          actionRef.current?.reloadAndRest?.()
          return false;
        }
      },
      onDelete: async (value: any) => {
        var val = await deleteDiscount({
          id: value
        });

        if (val.errorCode === '200') {
          message.success('删除成功');
          return true;
        } else {
          message.error(val.errorMessage);
          return false;
        }
      }
    }}/>

         <DrawerForm title='规则创建' onVisibleChange={setShowCreate} visible={showCreate} onFinish={async (values: any) => {
      var val = await addDiscount(values);

      if (val.errorCode === '200') {
        message.success('提交成功');
        actionRef.current?.reloadAndRest?.();
        return true;
      } else {
        message.error(val.errorMessage);
        return false;
      }
    }}>
           {/* <ProFormText name='ruleCode' label='规则编码' placeholder='请输入规则编码' rules={[{
        required: true
      }]}/> */}
           <ProFormSelect name='ruleType' rules={[{
        required: true
      }]} label='价格体系' options={Object.keys(priceOption()).map((item:any)=>{
        return {label:priceOption()[item].text,value:item}
      })} placeholder='请选择'/>
           <ProFormSelect name='productName' label='产品名称' placeholder='请输入产品名称' options={proData} rules={[{
        required: true
      }]} />
           <ProFormDigit name='discountNum' label='数量≥' placeholder='请输入' rules={[{
        required: true
      }]}/>
           <ProFormDigit name='discountNum2' label='数量≤' placeholder='请输入'/>
           <ProFormDigit name='discountPrice' label='优惠后价格' placeholder='请输入优惠后价格' rules={[{
        required: true
      }]}/>
            <ProFormTextArea name='ruleInfo' label='规则说明' placeholder='请输入规则说明'/>
         </DrawerForm>
         
  </PageContainer>;
});